package cybercode.carsaleserver.config.redis;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;


@Configuration
@Log4j2
public class LettuceConfig {

    @Value("${redis.database}")
    private int database;

    @Value("${redis.host}")
    private String host;

    @Value("${redis.port}")
    private int port;

    @Value("${redis.password}")
    private CharSequence password;

    @Value("${redis.timeout}")
    private long timeout;



    private RedisURI createRedisURI() {

        return RedisURI.Builder
                .redis(host)
                .withPort(port)
                .withTimeout(Duration.ofMillis(timeout))
                .withPassword(password)
                .withDatabase(database)
                .build();
    }

    @Bean(destroyMethod = "close")
    StatefulRedisConnection<String, String> redisConnection(RedisClient redisClient) {
        return redisClient.connect();
    }

    @Bean(destroyMethod = "shutdown")
    RedisClient redisClient() {
        RedisURI ri = createRedisURI();
        log.info("Connect to redis! host:" + host + ":" + port + " pass:" + password + " dbIndex:" + database);
        return RedisClient.create(ri);
    }

    public RedisCommands<String, String> getSyncCommand(){
        return redisConnection(redisClient()).sync();
    }

}
